﻿/*
    Copyright Rain-Soft co.2009 
*/

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Text;

using Rmlife.Common;
using Rmlife.Config;
using Rmlife.Data;
using Rmlife.Model;

namespace Rmlife.Site
{
    /// <summary>
    /// 页面基类
    /// </summary>
    public class PageBase : Page
    {
        #region 变量
        /// <summary>
        /// 基本配置文件路径
        /// </summary>
        protected internal string configfile = WebConfigs.Paths.DataRoot + "general.config";
        /// <summary>
        /// 站点根路径
        /// </summary>
        protected internal string WEBROOT = string.Empty;
        /// <summary>
        /// 当前用户名
        /// </summary>
        protected internal string username;
        /// <summary>
        /// 当前用户的用户ID
        /// </summary>
        protected internal int userid;
        /// <summary>
        /// 当前用户的密码
        /// </summary>
        protected internal string password;
        /// <summary>
        /// 当前用户的特征串
        /// </summary>
        protected internal string userkey;
        /// <summary>
        /// 当前用户的用户组ID
        /// </summary>
        protected internal int usergroupid;
        /// <summary>
        /// 当前用户的用户组编号
        /// </summary>
        protected internal string accountgroupid;
      
        /// <summary>
        /// 当前用户的管理组ID
        /// </summary>
        protected internal int useradminid = 0;
        /// <summary>
        /// 当前用户的短消息数目
        /// </summary>
        protected internal int newpmcount = 0;
        /// <summary>
        /// 组标题
        /// </summary>
        protected internal string grouptitle;
        /// <summary>
        /// 当前IP地址
        /// </summary>
        protected internal string ip;
        /// <summary>
        /// 当前页面名称
        /// </summary>
        public string pagename = WebReq.GetPageName();
        /// <summary>
        /// 全局配置实例
        /// </summary>
        protected internal GeneralConfigInfo config;
   
     
#if DEBUG
        /// <summary>
        /// 查询次数统计
        /// </summary>
        public int querycount = 0;
        /// <summary>
        /// DEBUG：查询语句
        /// </summary>
        public string querydetail = "";
#endif
        #endregion

        /// <summary>
        /// 控件初始化时计算执行时间
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            m_processtime = (Environment.TickCount - m_starttick) / 1000;
            base.OnInit(e);
        }
        /// <summary>
        /// 当前页面开始载入时间(毫秒)
        /// </summary>
        public float m_starttick = Environment.TickCount;
        /// <summary>
        /// 当前页面执行时间(毫秒)
        /// </summary>
        public float m_processtime;
        /// <summary>
        /// 得到当前页面的载入时间供调用(单位:毫秒)
        /// </summary>
        /// <returns>当前页面的载入时间</returns>
        public float Processtime
        {
            get { return m_processtime; }
        }


        /// <summary>
        /// BasePage类构造函数
        /// </summary>
        public PageBase()
        {
            if (!Page.IsPostBack)
            {
                this.RegisterAdminPageClientScriptBlock();
            }

        }


        /// <summary>
        /// 注册提示信息JS脚本
        /// </summary>
        public void RegisterAdminPageClientScriptBlock()
        {
            string script = "<div id=\"success\" style=\"position:absolute;z-index:300;height:120px;width:284px;left:50%;top:50%;margin-left:-150px;margin-top:-80px;\">\r\n" +
                "	<div id=\"Layer2\" style=\"position:absolute;z-index:300;width:270px;height:90px;background-color: #FFFFFF;border:solid #000000 1px;font-size:14px;\">\r\n" +
                "		<div id=\"Layer4\" style=\"height:26px;background:#f1f1f1;line-height:26px;padding:0px 3px 0px 3px;font-weight:bolder;\">操作提示</div>\r\n" +
                "		<div id=\"Layer5\" style=\"height:64px;line-height:150%;padding:0px 3px 0px 3px;\" align=\"center\"><BR /><table><tr><td valign=top><img border=\"0\" src=\"../images/ajax_loading.gif\"  /></td><td valign=middle style=\"font-size: 14px;\" >正在执行当前操作, 请稍等...<BR /></td></tr></table><BR /></div>\r\n" +
                "	</div>\r\n" +
                "	<div id=\"Layer3\" style=\"position:absolute;width:270px;height:90px;z-index:299;left:4px;top:5px;background-color: #E8E8E8;\"></div>\r\n" +
                "</div>\r\n" +
                "<script> \r\n" +
                "document.getElementById('success').style.display = \"none\"; \r\n" +
                "</script> \r\n" +
                "<script type=\"text/javascript\" src=\"../js/divcover.js\"></script>\r\n";


            ClientScript.RegisterClientScriptBlock(this.GetType(), "Page", script);
        }


        public new void RegisterStartupScript(string key, string scriptstr)
        {
            key = key.ToLower();
            if ((key == "pagetemplate") || (key == "page"))
            {
                string script = "";

                if (key == "page")
                {
                    script = "<script> \r\n" +
                        "var bar=0;\r\n" +
                        "document.getElementById('success').style.display = \"block\";  \r\n" +
                        "document.getElementById('Layer5').innerHTML ='<BR>操作成功执行<BR>';  \r\n" +
                        "count() ; \r\n" +
                        "function count(){ \r\n" +
                        "bar=bar+4; \r\n" +
                        "if (bar<99) \r\n" +
                        "{setTimeout(\"count()\",100);} \r\n" +
                        "else { \r\n" +
                        "document.getElementById('success').style.display = \"none\";HideOverSels('success'); \r\n" +
                        scriptstr + "} \r\n" +
                        "} \r\n" +
                        "</script> \r\n" +
                        "<script> window.onload = function(){HideOverSels('success')};</script>\r\n";
                }

                if (key == "pagetemplate")
                {
                    script = "<script> \r\n" +
                        "var bar=0;\r\n success.style.display = \"block\";  \r\n" +
                        "document.getElementById('Layer5').innerHTML = '<BR>" + scriptstr + "<BR>';  \r\n" +
                        "count() ; \r\n" +
                        "function count(){ \r\n" +
                        "bar=bar+4; \r\n" +
                        "if (bar<99) \r\n" +
                        "{setTimeout(\"count()\",100);} \r\n" +
                        "else { \r\n" +
                        "document.getElementById('success').style.display = \"none\";HideOverSels('success'); \r\n" +
                        "}} \r\n" +
                        "</script> \r\n" +
                        "<script> window.onload = function(){HideOverSels('success')};</script>\r\n";
                }

                ClientScript.RegisterStartupScript(this.GetType(), key, script);

            }
            else
            {

                ClientScript.RegisterStartupScript(this.GetType(), key, scriptstr);
            }
        }

        public void CallBaseRegisterStartupScript(string key, string scriptstr)
        {

            ClientScript.RegisterStartupScript(this.GetType(), key, scriptstr);
        }

        /// <summary>
        /// js执行
        /// </summary>
        /// <param name="jscriptId"></param>
        /// <param name="jsStr"></param>
        public void Execute_JS(string jscriptId, string jsStr)
        {
            string js = "<script language=javascript>";
            js += jsStr;
            js += "</script>";

            ClientScript.RegisterStartupScript(this.GetType(), jscriptId, js);
        }



        /// <summary>
        /// 提示信息
        /// </summary>
        /// <returns></returns>
        protected string GetShowMessage()
        {
            string message = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
            message += "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><title>您没有权限运行当前程序!</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">";
            message += "<link href=\"images/css.css\" type=\"text/css\" rel=\"stylesheet\"></head><body><br><br><div style=\"width:100%\" align=\"center\">";
            message += "<div align=\"center\" style=\"width:660px; border:1px dotted #FF6600; background-color:#FFFCEC; margin:auto; padding:20px;\"><img src=\"../images/hint.gif\" border=\"0\" alt=\"提示:\" align=\"absmiddle\" width=\"11\" height=\"13\" /> &nbsp;";
            message += "您没有权限运行当前程序,请您以超级管理员身份登陆后台进行操作!</div></div></body></html>";
            return message;
        }

        public void LoadRegisterStartupScript(string key, string scriptstr)
        {
            string message = "程序执行中... <BR /> 当前操作可能要运行一段时间.<BR />您可在此期间进行其它操作<BR /><BR />";

            string script = "<script> \r\n" +
                "var bar=0;\r\n success.style.display = \"block\";  \r\n" +
                "document.getElementById('Layer5').innerHTML ='" + message + "';  \r\n" +
                "count() ; \r\n" +
                "function count(){ \r\n" +
                "bar=bar+2; \r\n" +
                "if (bar<99) \r\n" +
                "{setTimeout(\"count()\",100);} \r\n" +
                "else { \r\n" +
                "	document.getElementById('success').style.display = \"none\";HideOverSels('success'); \r\n" +
                scriptstr + "} \r\n" +
                "} \r\n" +
                "</script> \r\n" +
                "<script> window.onload = function(){HideOverSels('success')};</script>\r\n";

            CallBaseRegisterStartupScript(key, script);

        }

        private bool saveState = false;

        private bool IsRestore
        {
            get
            {
                if (Request.QueryString["IsRestore"] != null && Request.QueryString["IsRestore"] == "1" && Request.Form["__VIEWSTATE"] == null)
                    return true;
                else
                    return false;
            }
        }

        private string RestoreKey
        {
            get { return Request.QueryString["key"]; }
        }

        public bool SavePageState
        {
            get { return this.saveState; }
            set { this.saveState = value; }
        }

        private NameValueCollection postData = null;

        private NameValueCollection PostData
        {
            get
            {
                if (this.IsRestore)
                    return this.postData;
                return Request.Form;
            }
        }
        /// <summary>
        /// 不附加 OnLoad
        /// </summary>
        public bool CleanPage { get; set; }
        /// <summary>
        /// 附加关闭按钮
        /// </summary>
        public bool CloseButton { get; set; }
        /// <summary>
        /// 附加信息
        /// </summary>
        public string MoreText { get; set; }

        protected override void OnLoad(EventArgs e)
        {
            if (this.IsRestore)
            {
                ArrayList modifiedControls = new ArrayList();
                foreach (string key in PostData.AllKeys)
                {
                    System.Web.UI.Control control = FindControl(key);
                    if (control is IPostBackDataHandler)
                        if (((IPostBackDataHandler)control).LoadPostData(key, PostData))
                            modifiedControls.Add(control);
                }
                // 发生 PostDataChanged 事件在所有已变动的控件上:
                foreach (IPostBackDataHandler control in modifiedControls)
                    control.RaisePostDataChangedEvent();
            }
            base.OnLoad(e);

            if (CloseButton)
            {
                string headerStr = "";
                headerStr += "<div align='right' style=''>";

                headerStr += "" + MoreText;

                headerStr += "&nbsp;<span><a href='javascript:void(0);' onclick='WinClose()' title='关闭窗口' style='text-decoration:none;color:#333;'><img src='../images/del.gif' style='vertical-align:middle'> 关闭窗口</a></span>";

                headerStr += "</div>";

                this.ClientScript.RegisterClientScriptBlock(this.GetType(), "Form1", headerStr);
            }
            else
            {


                if (CleanPage) return;


                string headerStr = "";

                //<script type=\"text/javascript\" src=\"../js/AjaxHelper.js\"></script><script type='text/javascript'>\nfunction ResetShortcutMenu(){top.mainFrame.LoadShortcutMenu();}\nfunction FavoriteFunction(url){\nAjaxHelper.Updater('../UserControls/favoritefunction','resultmessage','url='+url,ResetShortcutMenu);\n}\n</script>\n";

                headerStr += "<div class=\"topbar\">";

                if (!string.IsNullOrEmpty(MoreText))
                {
                    headerStr += "<table><tr>";

                    headerStr += "<td class=\"tdl\">";

                    headerStr += "" + MoreText;

                    headerStr += "</td>";

                    headerStr += "<td class=\"tdr\">";
                }

                headerStr += "<div align=\"right\">";

                if (newpmcount > 0)
                {
                    headerStr += "&nbsp;<span class=\"newpm\"><img src='../images/newpm.gif' style='vertical-align:middle'> <a href=\"javascript:void(0)\" onclick=\"javascript:top.topFrame.locationurl('28','6','28','CompanyManage/PmList.aspx');\">您有" + newpmcount + "条互动消息未处理!</a></span>";

                    if (!string.IsNullOrEmpty(MoreText))
                    {
                        headerStr += "<br />";
                    }
                }

                headerStr += "&nbsp;<span class=\"hellouser\">您好，<b>" + username + "</b> （" + grouptitle + "）</span>";

                //headerStr += "&nbsp;<span><a href='javascript:void(0);' onclick='top.mainFrame.showNavigation()' title='按ESC键或点击链接显示导航菜单' style='text-decoration:none;color:#333;'><img src='../images/navigation.gif' style='vertical-align:middle'> 快捷导航</a></span>";

                headerStr += "&nbsp;<!--<span><a href='" + WEBROOT + "logout.aspx' title='退出系统' style='text-decoration:none;color:#333;'><img src='../images/del.gif' style='vertical-align:middle'> 退出登录</a></span>-->";

                headerStr += "</div>";

                if (!string.IsNullOrEmpty(MoreText))
                {
                    headerStr += "</td></tr></table>";
                }

                headerStr += "</div>";

                this.ClientScript.RegisterClientScriptBlock(this.GetType(), "Form1", headerStr);
                //this.ClientScript.RegisterClientScriptBlock(this.GetType(), "Navigation", "<script type='text/javascript'>if(document.documentElement.addEventListener){document.documentElement.addEventListener('keydown', top.mainFrame.resetEscAndF5, false);}else if(document.documentElement.attachEvent){document.documentElement.attachEvent('onkeydown', top.mainFrame.resetEscAndF5);}</script>");
            }
        }

        private void RegisterMessage(string scriptstr, bool autoHidd, string autoJumpUrl)
        {
            string script = "<script type='text/javascript'>\r\n" +
                    "var bar=0;\r\n" +
                    "document.getElementById('success').style.display = \"block\";\r\n" +
                    "document.getElementById('Layer5').innerHTML = '<BR>" + scriptstr + "<BR>';\r\n";
            if (autoHidd)
            {
                script += "count();\r\n" +
                "function count()\r\n" +
                "{\r\n" +
                "\tbar=bar+4;\r\n" +
                "\tif (bar<99)\r\n" +
                "\t{\r\n" +
                "\t\tsetTimeout(\"count()\",200);\r\n" +
                "\t}\r\n" +
                "\telse\r\n" +
                "\t{\r\n";
                if (autoJumpUrl == "")
                {
                    script += "\t\tdocument.getElementById('success').style.display = \"none\";HideOverSels('success');\r\n";
                }
                else
                {
                    script += "\t\twindow.location='" + autoJumpUrl + "';\r\n";
                }
                script += "\t}\r\n" +
                          "}\r\n";
            }
            script += "</script>\r\n" +
                      "<script> window.onload = function(){HideOverSels('success')};</script>\r\n";

            ClientScript.RegisterStartupScript(this.GetType(), "resultMessage", script);
        }

        protected void RegisterMessage(string scriptstr, string autoJumpUrl)
        {
            RegisterMessage(scriptstr, true, autoJumpUrl);
        }

        protected void RegisterMessage(string scriptstr, bool autoHidd)
        {
            RegisterMessage(scriptstr, autoHidd, "");
        }

        protected void RegisterMessage(string scriptstr)
        {
            RegisterMessage(scriptstr, false);
        }
        #region 调用自定义的方法对VIEWSTATE进行操作
        protected void MySavePageState(object viewState)
        {
            string keyid = userid + "_" + this.GetType().Name.Trim();
            MyControlContainer dcc = MyControlContainer.GetContainer();
            dcc.AddNormalComponent(keyid, viewState);
        }

        protected object MyLoadPageState()
        {
            string keyid = userid + "_" + this.GetType().Name.Trim();
            MyControlContainer dcc = MyControlContainer.GetContainer();
            object viewState = (object)dcc.GetNormalComponentDataObject(keyid);
            dcc.RemoveComponentByName(keyid);
            if (viewState != null) return viewState;
            else return null;
        }
        #endregion

        #region 把VIEWSTATE以组件的形式存入容器
        protected override void SavePageStateToPersistenceMedium(object viewState)
        {
            base.SavePageStateToPersistenceMedium(viewState);
        }

        protected override object LoadPageStateFromPersistenceMedium()
        {
            object o = new object();
            try
            {
                o = base.LoadPageStateFromPersistenceMedium();
            }
            catch
            {
                o = null;
            }
            return o;
        }
        #endregion


        /// <summary>
        /// OnUnload事件处理
        /// </summary>
        /// <param name="e"></param>
        protected override void OnUnload(EventArgs e)
        {
#if DEBUG
            //  System.Web.HttpContext.Current.Response.Clear();
            //  System.Web.HttpContext.Current.Response.Write(querydetail);
            // System.Web.HttpContext.Current.Response.End();
#endif

            base.OnUnload(e);
        }

        private bool ValidateUserPermission()
        {
            //if (!usergroupinfo.sCompanyGroupRole.AllowVisit && useradminid != 1)
            //{
            //    ShowMessage("抱歉, 您所在的用户组不允许访问本站.", 0);
            //    return false;
            //}

            return true;
        }

        public void ShowMessage(byte mode)
        {
            ShowMessage("", mode);
        }

        public void ShowMessage(string hint, byte mode)
        {
            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.Write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head><title>");
            string title;
            string body;
            switch (mode)
            {
                case 1:
                    title = "网站已关闭";
                    body = "网站已关闭";
                    break;
                case 2:
                    title = "禁止访问";
                    body = hint;
                    break;
                default:
                    title = "提示";
                    body = hint;
                    break;
            }
            System.Web.HttpContext.Current.Response.Write(title);
            System.Web.HttpContext.Current.Response.Write("</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
            System.Web.HttpContext.Current.Response.Write("<style type=\"text/css\"><!-- body { margin: 20px; font-family: Tahoma, Verdana; font-size: 14px; color: #333333; background-color: #FFFFFF; }a {color: #1F4881;text-decoration: none;}--></style></head><body><div style=\"border: #cccccc solid 1px; padding: 20px; width: 500px; margin:auto\" align=\"center\">");
            System.Web.HttpContext.Current.Response.Write(body);
            System.Web.HttpContext.Current.Response.Write("</div><br /><br /><br /><div style=\"border: 0px; padding: 0px; width: 500px; margin:auto\"><strong>当前服务器时间:</strong> ");
            System.Web.HttpContext.Current.Response.Write(Utils.GetDateTime());
            System.Web.HttpContext.Current.Response.Write("<br /><strong>当前页面</strong> ");
            System.Web.HttpContext.Current.Response.Write(pagename);
            System.Web.HttpContext.Current.Response.Write("<br /><strong>可选择操作:</strong> ");
            if (userkey == "")
            {
                System.Web.HttpContext.Current.Response.Write("<a href=\"" + BaseConfigs.GetSitePath + "login.aspx\">登录</a>");
            }
            else
            {
                System.Web.HttpContext.Current.Response.Write("<a href=\"" + BaseConfigs.GetSitePath + "logout.aspx?userkey=" + userkey + "\">退出</a>");

            }
            System.Web.HttpContext.Current.Response.Write("</div></body></html>");
            System.Web.HttpContext.Current.Response.End();
        }

        /// <summary>
        /// 检查当前用户是否是管理员
        /// </summary>
        /// <returns></returns>
        public bool CheckAdministrator()
        {
            return this.useradminid == 1;
        }

        /// <summary>
        /// 检查当前用户是否是普通用户权限
        /// </summary>
        /// <returns></returns>
        public bool CheckMyRole()
        {
            return usergroupid > -1 && useradminid == 0;
        }

        /// <summary>
        /// 检查当前用户是否有权限操作
        /// </summary>
        /// <returns></returns>
        public bool CheckRole(bool role)
        {
            return role || CheckAdministrator();
        }
    }
}
